package com.hjh.net.moshi

import com.drake.net.convert.JSONConvert
import com.hjh.net.moshi.adapter.DateAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import org.json.JSONObject
import java.lang.reflect.Type

/**
 * @author hjh
 * @version 1.0
 * @since 1.0
 * @date 2024/4/2
 * @qq 3472903821
 * @description moshi库转换，配合net框架使用
 */
class MoshiConverter : JSONConvert(code = "code", message = "msg", success = "200") {

    override fun <R> String.parseBody(succeed: Type): R? {
        val string = try {
            JSONObject(this).getString("data")
        } catch (e: Exception) {
            this
        }
        return moshi.adapter<R>(succeed).fromJson(string)
    }

    companion object {
        private val moshi = Moshi.Builder()
            .add(DateAdapter())
            .add(KotlinJsonAdapterFactory())
            .build()
    }
}